package com.gitee.wsl.common.ui.ext.drawScope

import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp


/**
 * Draws checker background, [dstBitmap] and [block]. [DrawScope.drawImage] is drawn
 * with [BlendMode.SrcIn] to clip [dstBitmap] to what's drawn inside [block]
 */
fun DrawScope.drawBlockWithCheckerAndLayer(
    dstBitmap: ImageBitmap,
    block: DrawScope.() -> Unit,
) {
    drawChecker()
    drawWithLayer {

        val canvasWidth = size.width.toInt()
        val canvasHeight = size.height.toInt()

        // Destination
        block()

        // Source
        drawImage(
            image = dstBitmap,
            dstSize = IntSize(canvasWidth, canvasHeight),
            blendMode = BlendMode.SrcIn
        )
    }
}

/**
 * Draw checker background
 */
fun DrawScope.drawChecker() {

    val width = this.size.width
    val height = this.size.height

    val checkerWidth = 10.dp.toPx()
    val checkerHeight = 10.dp.toPx()

    val horizontalSteps = (width / checkerWidth).toInt()
    val verticalSteps = (height / checkerHeight).toInt()

    for (y in 0..verticalSteps) {
        for (x in 0..horizontalSteps) {
            val isGrayTile = ((x + y) % 2 == 1)
            drawRect(
                color = if (isGrayTile) Color.LightGray else Color.White,
                topLeft = Offset(x * checkerWidth, y * checkerHeight),
                size = Size(checkerWidth, checkerHeight)
            )
        }
    }
}